<template>
  <div>
    <el-dialog v-if="dialogVisible"
               v-model="dialogVisible"
               title="选择地址"
               width="75%"
               top="10vh"
               :before-close="handleClose">

      <div id="map-container">

        <div class="inputs ">

          <el-form label-position="top">
            <el-form-item label="搜索地址："
                          prop="">
              <el-input v-model="location"
                        id="tipinput"
                        class="mt10"
                        placeholder="请搜索地址"></el-input>
            </el-form-item>
            <div @click="choiceAddress"
                 class="choiceAddressBox">
              <el-icon color="#4478E6"
                       size="18">
                <FolderChecked />
              </el-icon>
              <div class="ml10 fb">
                从地址库选择
              </div>
            </div>
            <el-form-item label="选中地址："
                          prop="">
              <div class="info">
                {{ inputCity }}
              </div>
            </el-form-item>
            <el-form-item label="详细地址："
                          prop="">
              <el-input v-model="inputDetails"
                        @input="inputDetails = $input.inputLimit('D10006',inputDetails)"
                        placeholder="请输入详细地址（中文、英文、数字）"
                        class="mt10"></el-input>
            </el-form-item>
            <div class="tar">

              <el-button v-preventReClick
                         type=""
                         plain
                         class="btnSub mt10"
                         @click="handleClose">取消</el-button>
              <el-button v-preventReClick
                         type="primary"
                         class="btnSub mt10"
                         @click="saveAddress">保存并使用</el-button>
              <el-button v-preventReClick
                         type="primary"
                         class="btnSub mt10"
                         @click="btnSubmit">确定</el-button>

            </div>
          </el-form>

        </div>
      </div>

      <el-dialog v-model="innerVisible"
                 v-if="innerVisible"
                 width="70%"
                 title="地址库"
                 top="15vh"
                 append-to-body>
        <div class="addressBox boxContent">

          <div class="searchList">
            <el-form :model="params"
                     ref="FormInstance "
                     class="boxFrom">
              <div class="searchBox">
                <template v-for="(item, index) in totalInputColumns"
                          :key="index">
                  <el-form-item v-if="item.type == 'input'"
                                :label="item.title">
                    <el-input v-model="params[item.key]"
                              clearable
                              :placeholder="item.label"></el-input>
                  </el-form-item>
                  <el-form-item v-if="item.type == 'time'"
                                :label="item.title">
                    <el-date-picker v-model="params[item.key]"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    :placeholder="item.label" />
                  </el-form-item>
                  <el-form-item v-if="item.type == 'select'"
                                :label="item.title">
                    <el-select v-model="params[item.key]"
                               :placeholder="item.label"
                               clearable
                               v-if="item.key == 'companyId'">
                      <el-option />
                    </el-select>

                    <el-cascader v-model="params[item.key]"
                                 :options="propsCity"
                                 :props="props"
                                 :placeholder="item.label"
                                 clearable
                                 v-if="item.key == 'city'" />
                    <el-select v-model="params[item.key]"
                               v-if="item.key == 'childCompanyId' && userInfor.companyType == 1"
                               :placeholder="item.label"
                               clearable>
                      <el-option v-for="i in totalInputColumnsOption.getChildCompanyByUserIdList"
                                 :key="i"
                                 :label="i.name"
                                 :value="i.id" />134
                    </el-select>
                  </el-form-item>
                </template>

                <el-button v-preventReClick
                           type="primary"
                           plain
                           @click="handleAction('query')">搜索</el-button>
                <el-button v-preventReClick
                           @click="handleAction('reset')">重置</el-button>
              </div>
            </el-form>

          </div>

          <div class="tabaleBox">
            <el-table :data="addressData"
                      style="width: 100%"
                      :header-cell-style="{ color: '#000' }"
                      v-loading="loading">
              <el-table-column prop="addrProvince"
                               label="省份"
                               show-overflow-tooltip
                               align="left"
                               width="100" />
              <el-table-column prop="addrCity"
                               label="城市"
                               show-overflow-tooltip
                               align="left"
                               width="100">
              </el-table-column>
              <el-table-column prop="addrDistrict"
                               label="城区"
                               show-overflow-tooltip
                               align="left"
                               width="100">
              </el-table-column>

              <el-table-column prop="addr"
                               label="地址"
                               show-overflow-tooltip
                               align="left" />
              <el-table-column prop="addrDetails"
                               label="详细地址"
                               show-overflow-tooltip
                               align="left" />

              <el-table-column prop="btns"
                               label="操作"
                               show-overflow-tooltip
                               align="center"
                               width="110"
                               fixed="right">
                <template #default="scope">
                  <div class="tableBtn flex_sb">
                    <div @click="handleAction('delete', scope.row)"
                         class="btn error">
                      删除
                    </div>
                    <div @click="handleAction('choice', scope.row)"
                         class="btn primary">
                      选择
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <el-pagination background
                           v-model:current-page="params.pageNum"
                           v-model:page-size="params.pageSize"
                           :page-sizes="[10, 20, 30, 50]"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="totalSize"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange" />
          </div>
        </div>

      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
export default {
  props: {
    type: {
      type: String,
      default: "",
    },
    cityName: {
      type: String,
      default: "",
    },

  },
  data () {
    return {
      loading: false,
      innerVisible: false,
      mapCenter: null,
      inputCity: '',
      inputDetails: '',
      dialogVisible: false,
      location: "", // input的内容
      map: null, //
      lnglat: [], // 经纬度数组 [lng,lat]
      auto: null,
      placeSearch: null,
      markers: [],
      driving: null,
      AMap: null,
      selectAddress: null,
      params: {
        pageSize: 10,
        pageNum: 1,
        companyId: '',
      },
      addressData: [],
      totalInputColumns: [
        { title: '地址名称', key: "addrName", label: "请输入地址", type: "input" },

      ],
      totalSize: 0,
    };
  },

  mounted () {
    this.params.companyId = this.$route.query.companyId
    window._AMapSecurityConfig = {
      securityJsCode: "25efa033366760fb46f7d40fae7cfbb6", // 申请key对应的秘钥 -> 注意了，如果不搭配密钥使用，搜索将没有结果
    };
    // 初始化地图
    this.$nextTick(() => {
      this.initMap();

    });
  },

  methods: {


    handleAction (type, data) {
      switch (type) {

        case "query": //查询
          this.choiceAddress();
          break;
        case "reset": // 重置
          this.params.pageSize = 10
          this.params.pageNum = 1
          this.params.addrName = ''
          break;
        case "choice": // 选择
          this.selectAddress = {
            name: data.addr,
            lng: data.addrLongitude,
            lat: data.addrLatitude,
            adcode: data.adcode,
            city: data.addrCity,
            district: data.addrDistrict,
            province: data.addrProvince,
          };
          this.innerVisible = false
          this.mapCenter = [data.addrLongitude, data.addrLatitude]
          // this.initMapCreate()
          this.inputCity = data.addr
          this.inputDetails = data.addrDetails
          this.map.setCenter(this.mapCenter)
          this.setMarker(this.mapCenter);

          break;
        case "delete": // 删除
          ElMessageBox.confirm("请确认是否删除该地址?", "删除地址", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$post("companyAddress/delete", { id: data.id }).then((res) => {
                this.choiceAddress();
                ElMessage({
                  type: "success",
                  message: "已删除",
                });
              });
            })
            .catch(() => {
              this.choiceAddress();
              ElMessage({
                type: "info",
                message: "已取消",
              });
            });

          break;
      }
    },
    // 选择地址
    choiceAddress () {
      this.loading = true
      this.$get('companyAddress/query', this.params).then(res => {
        if (res.code == 200) {
          this.addressData = res.data.data
          this.totalSize = res.data.total
          this.innerVisible = true
        }
        this.loading = false
      })
    },
    // 保存地址
    saveAddress () {
      if (this.inputCity == '') {
        return ElMessage.error('请选择地址')
      }
      this.$post('companyAddress/save', {
        "companyId": this.params.companyId, //公司id
        "addrLongitude": this.selectAddress.lng, //经度
        "addrLatitude": this.selectAddress.lat, //纬度
        "addr": this.inputCity, //地址
        "addrDetails": this.inputDetails, //详细地址
        "addrProvince": this.selectAddress.province, //省
        "addrCity": this.selectAddress.city, //市
        "addrDistrict": this.selectAddress.district, //区
        "adcode": this.selectAddress.adcode // code
      }).then(res => {
        if (res.code == 200) {
          ElMessage.success('保存成功')
          this.btnSubmit()
        }
      })
    },

    locateCityCenter (cityName) {
      const geocoder = new AMap.Geocoder()
      geocoder.getLocation(cityName, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          if (result.geocodes.length > 0) {
            const cityCenter = result.geocodes[0].location
            this.mapCenter = [cityCenter.lng, cityCenter.lat]
            // this.map.setCenter(cityCenter)
            this.initMapCreate()
          } else {
            console.error('未能找到该城市的中心点')
          }
        } else {
          console.error(`地理编码失败: ${result.info}`)
        }
      })
    },
    handleClose () {
      this.location = "";
      this.inputDetails = ''
      this.dialogVisible = false;
    },
    btnSubmit () {
      if (this.selectAddress == null) {
        return ElMessage.error('请选择地址')
      }
      this.selectAddress.name = this.selectAddress.name + (this.inputDetails != '' ? '(' + this.inputDetails + ')' : '')
      this.$emit("mapData", this.selectAddress, this.type);
      this.location = "";
      this.dialogVisible = false;
    },
    initMap () {
      console.log('this.mapCenter', this.mapCenter);
      if (this.mapCenter?.length - 0 != 0) {
        this.initMapCreate()
      } else if (this.cityName) {
        this.locateCityCenter(this.cityName)
      } else {
        this.initMapCreate()
      }
    },
    initMapCreate () {
      AMapLoader.load({
        key: "7eb82e62a307f9670544abd0b215514a", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Driving",
          "AMap.DragRoute",
          "AMap.Geocoder",
        ],
      })
        .then((AMap) => {
          const _this = this;
          _this.map = new AMap.Map("map-container", {
            // 设置地图容器id
            viewMode: "3D", //  是否为3D地图模式
            zoom: 13, // 初始化地图级别
            center: _this.mapCenter || null, //中心点坐标
            resizeEnable: true,
          });

          // 监听鼠标点击事件
          setTimeout(() => {
            _this.map.on("click", _this.clickMapHandler);
            // 函数调用（写入你先所需要的事件函数）
            _this.searchMap(); // POI关键字搜索
            if (this.mapCenter?.length - 0 != 0) {
              _this.setMarker(_this.mapCenter)
            }
            // ...其他
          }, 300);
        })
        .catch((e) => {
          console.log(e);
        });

    },
    clickMapHandler (e) {
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
    },
    //  添加标记
    setMarker (lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker); // 在data中记录标记点
      this.lngToAddress(lnglat);

    },
    /* 地址逆解析 */
    lngToAddress (lngLat) {
      let _this = this;
      var geocoder;
      geocoder = new AMap.Geocoder({});
      geocoder.getAddress(lngLat, function (status, result) {
        console.log("status", status, result);
        if (status === "complete" && result.regeocode) {
          _this.selectAddress = {
            name: result.regeocode.formattedAddress,
            lng: lngLat[0],
            lat: lngLat[1],
            adcode: result.regeocode.addressComponent.adcode,
            city: result.regeocode.addressComponent.city,
            district: result.regeocode.addressComponent.district,
            province: result.regeocode.addressComponent.province,
          };
          _this.inputCity = result.regeocode.formattedAddress

        } else {
          console.log("根据经纬度查询地址失败");
        }
      });
    },
    // 删除之前后的标记点
    removeMarker () {
      // 判断是否存被标记的点，有--->移除
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
    // 地图关键字查询
    searchMap () {
      //   搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput",
      });
      //   //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      //   当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },

    //当选中某条搜索记录时触发
    selectSite (e) {
      console.log(e);
      if (!e.poi.location) {
        ElMessage({
          message: "获取地址错误，请重新获取",
          type: "error",
        });
        return;
      }
      this.lnglat = [e.poi.location.lng, e.poi.location.lat];
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name);
      this.lngToAddress([e.poi.location.lng, e.poi.location.lat])
    },
    //分页变化
    handleSizeChange () {
      this.params.pageNum = 1;
      methods.choiceAddress();
    },
    //表格翻页
    handleCurrentChange () {
      this.choiceAddress();
    },
  },
};
</script>

<style lang="scss">
.choiceAddressBox {
  cursor: pointer;
  margin-bottom: 10px;
  width: 156px;
  color: #4478e6;
  display: flex;
  align-items: center;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #4478e6;
  padding: 5px 16px;
}
.addressBox {
  padding: 10px 15px;
  height: 600px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .tabaleBox {
    flex: 1;
    overflow: hidden;
  }
  .searchList {
    .boxFrom {
      padding: 0px !important;
    }
  }
  .pagination {
    margin-top: 20px;
    height: 50px;
    display: flex;
    justify-content: center;
  }
}
.amap-sug-result {
  z-index: 10240 !important;
}
.btnSub {
  margin-left: 10px;
}
.topInput {
  margin-bottom: 10px;
}
#map-container {
  position: relative;
  width: 100%;
  height: 700px;
  top: 0;
  .inputs {
    padding: 20px;
    background: #fff;
    border-radius: 5px;
    position: absolute;
    right: 10px;
    top: 10px;
    width: 400px;
    z-index: 2;
  }
}
</style>
